<?php
class myDB {
  var $host = "localhost";
  var $user = "";
  var $pass = "";
  var $dbName = "";
  var $_dbh;
  var $debug = true;
  var $queries = array();
  var $error = "";
  var $_backtrace = false;
  var $_memgetus = false;

// Constructor
  function myDB ($param = array()){
    $this -> _backtrace = function_exists("debug_backtrace");
    $this -> _memgetus = function_exists("memory_get_usage");
    foreach ($param as $key => $value) {
      $this -> $key = $value;
    }
  }

  function &getConnection ($params = array()){
    static $connections = array();
    $params = array_merge(
      array(
        'host' => 'localhost',
        'user' => 'nobody',
        'pass' => ''
      ),
      $params
    );
    $key = $params['user'] . ":" . $params['pass'] . "@" .
           $params['host'] . (isset($params['port']) ? ":". $params['port'] : "");
    if(!isset($connections[$key])){
      $connections[$key] = new myDB($params);
      if(!$connections[$key] -> connect()) die("Can't connect to DB");
    }
    return $connections[$key];
  }

  function &getConnection2 ($path = "mysql://nobody@localhost"){
    static $connections = array();
    $params = parse_url($path);
    $params = array_merge(
      array(
        'host' => 'localhost',
        'user' => 'nobody',
        'pass' => ''
      ),
      $params
    );
    if(!isset($connections[$path]) || $connections[$path] === false){
      $c = new myDB($params);
      if($c -> connect()){
      	$connections[$path] =& $c;
        if(isset($params['path'])) $connections[$path] -> getDB(substr($params['path'], 1));
      } else {
        $connections[$path] = false;
      }
    }
    return $connections[$path];
  }

  function connect(){
    $h = $this -> host;
    if(isset($this -> port)) $h .= ":". intval($this -> port);
    $res = mysql_connect(
      $h,
      $this -> user,
      $this -> pass,
      false,
      MYSQL_CLIENT_COMPRESS
    );
    if($res === false){
      $this -> error = "Can't connect to DB on host: '{$this -> host}', user: '{$this -> user}', password: '{$this -> pass}'";
      if($this -> _backtrace) $this -> error .= "\n" . var_export(debug_backtrace(), true);
      return false;
    }
      $this -> _dbh = $res;
      return true;
  }

  function disconnect(){
    if(is_resource($this -> _dbh)) mysql_close($this -> _dbh);
  }

  function isConnected(){
    return is_resource($this -> _dbh) || mysql_ping($this -> _dbh);
  }

  function getDB ($dbName = ''){
    if(!$this -> isConnected()) return false;
    $dbName = ($dbName == '')? $this -> dbName : $dbName;
    @mysql_select_db($dbName, $this -> _dbh);
    if(mysql_errno($this -> _dbh) > 0){
      $this -> error = mysql_error($this -> _dbh);
      if($this -> _backtrace) $this -> error .= "\n" . var_export(debug_backtrace(), true);
      return false;
    }
    mysql_query("SET NAMES '". X2_SQL_DEFAULT_CHARSET ."'"); //SET character_set_results = NULL
    $this -> dbName = $dbName;
    return true;
  }

  function query($query, $buffered = false){
    if(!$this -> isConnected()) return false;
    $this -> error = "";
    if($this -> debug) $start = getmicrotime();
    if($buffered){
      $result = mysql_query(
        trim($query),
        $this -> _dbh
      );
    } else {
      $result = mysql_unbuffered_query(
        trim($query),
        $this -> _dbh
      );
    }
    if($this -> debug) {
      $report = $query . " [Time: ". (getmicrotime() - $start) ."]";
      $lq = strtolower($query); // DELETE, INSERT, REPLACE, or UPDATE?
      if(strpos($lq, "update") !== false ||
        strpos($lq, "delete") !== false ||
        strpos($lq, "insert") !== false ||
        strpos($lq, "replace") !== false){
        $report .= "[Changed: " . mysql_affected_rows($this -> _dbh) . "]";
      }
      if($this -> _memgetus){
        $report .= "[Memory: " . memory_get_usage() . " b]";
      }
      $this -> queries[] = $report;
    }
    if(mysql_errno($this -> _dbh) > 0){
      $this -> error = "[". mysql_errno($this -> _dbh) ."]". mysql_error($this -> _dbh);
      if($this -> _backtrace) $this -> error .= "\n" . var_export(debug_backtrace(), true);
      return false;
    }
    return $result;
  }

  function arrayQuery($query, $keyName = ''){
    if(!$this -> isConnected()) return false;
    $result = array();
    $this -> error = "";
    if($this -> debug) $start = getmicrotime();
    $res = mysql_unbuffered_query(
      trim($query),
      $this -> _dbh
    );
    if($this -> debug) {
      $report = $query . " [Time: ". (getmicrotime() - $start) ." sec]";
      if($this -> _memgetus){
        $report .= "[Memory: " . memory_get_usage() . " b]";
      }
      $this -> queries[] = $report;
    }
    if(mysql_errno($this -> _dbh) > 0){
      $this -> error = "[". mysql_errno($this -> _dbh) ."]". mysql_error($this -> _dbh);
      if($this -> _backtrace) $this -> error .= "\n" . var_export(debug_backtrace(), true);
      return false;
    }
    while($r = mysql_fetch_assoc($res)){
      if($keyName == '' ||  !isset($r[$keyName])) $result[] = $r;
          else $result[$r[$keyName]] = $r;
    }
    return $result;
  }

  function getResult($res){
    if(!is_resource($res)) return false;
    $result = array();
    while($r = mysql_fetch_assoc($res)){
      $result[] = $r;
    }
    return $result;
  }

  function getRow($res){
    return (is_resource($res))? mysql_fetch_assoc($res) : false;
  }

  function getField($res, $name){
    if(!is_resource($res)) return false;
    $row = mysql_fetch_assoc($res);
    return (isset($row[$name]))? $row[$name] : false;
  }

  function getSingle($query, $name){
    if(!$this -> isConnected()) return false;
    return $this -> getField(
      $this -> query($query),
      $name
    );
  }

  function getNumRows($query){    if(strtoupper(substr(trim($query), 0, 6)) != "SELECT") return false;
    if(!$this -> isConnected()) return false;
    $res = $this -> query($query, true);
    $result = false;
    if(is_resource($res)){      $result = mysql_num_rows($res);
      mysql_free_result($res);
    }
    return $result;  }

  function wasChanged() {
    if(!$this -> isConnected()) return 0;
    return mysql_affected_rows($this -> _dbh);
  }

  function lastId() {
    if(!$this -> isConnected()) return false;
    return mysql_insert_id ($this -> _dbh);
  }

  function free ($res) {
    return(is_resource($res))? mysql_free_result($res) : false;
  }

  function safe($str){
    return $this -> quote($str);
  }

  function quote($str){
    return mysql_real_escape_string ($str, $this -> _dbh);
  }
}
?>